<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>添加</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/layui/css/layui.css">

</head>

<body>
    <div style="padding: 20px;">
        <form class="layui-form layui-form-pane" action="" lay-filter="addForm">
            <div class=" layui-card-body  gridAuto">
                <div class="layui-form-item">
                    <label class="layui-form-label">部门名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" lay-verify="required" autocomplete="off" placeholder="请输入部门名称"
                            class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">部门代码</label>
                    <div class="layui-input-block">
                        <input type="text" name="code" autocomplete="off" placeholder="请输入部门代码" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">所属区划</label>
                    <div class="layui-input-block">
                        <div class="layui-inline" id="selectarea">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">部门地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="address" autocomplete="off" placeholder="请输入部门地址" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">联系人</label>
                    <div class="layui-input-block">
                        <input type="text" name="lxr" autocomplete="off" placeholder="请输入联系人" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">联系电话</label>
                    <div class="layui-input-block">
                        <input type="text" name="phone" autocomplete="off" placeholder="请输入联系电话" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">部门状态</label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="status" lay-skin="switch" lay-filter="switchTest" title="启用|禁用">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">排序</label>
                    <div class="layui-input-block">
                        <input type="number" lay-affix="number" min="0" name="order_num" value="0" class="layui-input">
                    </div>
                </div>


                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">备注说明</label>
                    <div class="layui-input-block">
                        <textarea name="memo" placeholder="请输入备注" class="layui-textarea"></textarea>
                    </div>
                </div>

                <div class="layui-form-item" style="text-align: center; margin-top: 30px;">
                    <input type="hidden" name="id">
                    <input type="hidden" name="areaid" id="areaId">
                    <input type="hidden" name="depth" id="depth">
                    <input type="hidden" name="areacode" id="areacode">
                    <button type="submit" class="layui-btn layui-btn-normal" lay-submit
                        lay-filter="YjbtnSave">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
    <script src="/layui/layui.js"></script>
    <script>
        layui.use(function () {

            var form = layui.form
                , admin = parent.layui.admin
                , table = parent.layui.table
                , setter = layui.setter
            $ = layui.$;


            // 通用获取URL参数方法
            function getQueryParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return decodeURIComponent(r[2]);
                return null;
            }
            // 获取URL参数
            var pid = getQueryParam('pid') == '' ? 0 : getQueryParam('pid');
            var parent_path = getQueryParam('path');
            // 获取所有区划数据（一次性加载）
            var areaData = []; // 存储完整的区划数据
            var currentAreaPath = []; // 存储当前选中的区划路径

            // 初始化区划数据
            function initAreaData() {
                admin.req({
                    url: 'sysarea/getarealist',
                    data: { page: 1, limit: 10000 }, // 确保获取全部数据
                    done: function (res) {
                        areaData = res.data.data;
                        initForm(); // 数据加载完成后初始化表单
                    }
                });
            }

            // 根据pid过滤子级数据
            function getChildrenByPid(pid) {
                return areaData.filter(function (item) {
                    return item.pid == pid;
                });
            }

            // 生成select元素
            function createSelect(pid, selectedId) {
                var children = getChildrenByPid(pid);
                if (children.length === 0) return '';

                var html = '<div class="layui-inline">' +
                    '<select lay-filter="areaSelect">' +
                    '<option value="">请选择</option>';

                children.forEach(function (item) {
                    var selected = selectedId == item.id ? 'selected' : '';
                    html += `<option value="${item.code}&${item.id}" ${selected}>${item.name}</option>`;
                });

                html += '</select>' +
                    '</div>';
                return html;
            }

            // 递归构建区划选择器
            function buildAreaSelectors(pidChain) {
                $('#selectarea').html('');
                var currentPid = 0;

                pidChain.forEach(function (id, index) {
                    var selector = createSelect(currentPid, id);
                    $('#selectarea').append(selector);
                    currentPid = id; // 下一级以当前ID为pid
                });
                form.render('select');
            }

            // 获取区划完整路径（核心逻辑）
            function findAreaPath(targetId) {
                var path = [];
                function findParent(id) {
                    var area = areaData.find(item => item.id == id);
                    if (area) {
                        path.unshift(area.id); // 向前插入实现正序
                        if (area.pid != 0) findParent(area.pid);
                    }
                }
                findParent(targetId);
                return path;
            }

            // 初始化表单
            function initForm() {
                var id = getQueryParam('id');
                if (id) { // 编辑模式
                    admin.req({
                        url: 'sysdept/GetDeptInfoByID/' + id,
                        done: function (res) {
                            if (res.successful) {
                                
                                // 填充基础字段
                                form.val('addForm', {
                                    "id": res.data.id,
                                    "name": res.data.name,
                                    "code": res.data.code,
                                    "order_num": res.data.order_num,
                                    "remark": res.data.remark,
                                    "status": res.data.status === 0,
                                    "areacode": res.data.areacode,
                                    "areaId": res.data.areaid,
                                    "depth": res.data.depth,
                                    "address": res.data.address,
                                    "lxr": res.data.lxr,
                                    "phone": res.data.phone,
                                    "memo": res.data.memo
                                });

                                // 处理区划选择
                                var areaId = res.data.areaid;
                                if (!areaId) {
                                    $('#selectarea').html(createSelect(0));
                                    form.render('select');
                                }
                                else {
                                    $('#areaId').val(areaId);
                                    $('#areacode').val(res.data.areacode);
                                    currentAreaPath = findAreaPath(areaId);
                                    buildAreaSelectors(currentAreaPath);
                                }
                            }
                        }
                    });
                } else { // 新增模式初始化空选择器
                    $('#selectarea').html(createSelect(0));
                    form.render('select');
                }
            }

            // 区划选择事件
            form.on('select(areaSelect)', function (data) {
                var value = data.value.split('&');
                var selectedId = value[1];

                // 更新当前路径
                var selectIndex = $(data.elem).parent().index();
                currentAreaPath = currentAreaPath.slice(0, selectIndex);
                currentAreaPath.push(parseInt(selectedId));

                // 清空后续选择器
                $(data.elem).closest('.layui-inline').nextAll().remove();

                // 添加下一级选择
                var nextChildren = getChildrenByPid(selectedId);
                if (nextChildren.length > 0) {
                    $('#selectarea').append(createSelect(selectedId));
                    form.render('select');
                }

                // 更新隐藏字段
                $('#areaId').val(currentAreaPath.slice(-1)[0]);
                $('#areacode').val(value[0]);
            });

            // 表单提交
            form.on('submit(YjbtnSave)', function (data) {
                if (!$('#areaId').val()) {
                    admin.msg_error('请选择所属区划！');
                    return false;
                }
                data.field.depth = parent_path.split(',').length - 1;
                var postData = {
                    ...data.field,
                    status: data.field.status ? 0 : 1,
                    pid: pid,
                    parent_path: parent_path,
                };

                admin.req({
                    url: postData.id ? 'sysdept/UpdateDept' : 'sysdept/adddept',
                    method: postData.id ? 'PUT' : 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(postData),
                    done: function (res) {
                        if (res.successful) {
                            parent.layer.closeAll();
                            table.reload('LAY-app-dept-list');
                            admin.msg_success(postData.id ? '更新成功！' : '添加成功！');
                        }
                        else {
                            admin.msg_error(res.msg);
                        }
                    }
                });
            });

            // 初始化执行
            initAreaData();
        });

    </script>
</body>

</html>